package com.i2863.tools.weixinmp.util;

import com.i2863.tools.weixinmp.util.HttpSessionUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * Created by xuweiwei on 2017/8/16.
 */
public class UploadUtil {
    private static CloseableHttpClient httpClient = HttpSessionUtils.buildHttpClient();


    public static String  upload(String url,String refer) throws IOException {
        InputStream is = HttpSessionUtils.httpContent(httpClient, url, refer);
        QiniuUpload qiniuUpload = QiniuManager.get();
        String key = UUID.randomUUID().toString().replace("-","");
        return qiniuUpload.upload(key,IOUtil.input2byte(is));
    }


    public static String  upload(String url) throws IOException {
        InputStream is = HttpSessionUtils.httpContent(httpClient, url);
        QiniuUpload qiniuUpload = QiniuManager.get();
        String key = UUID.randomUUID().toString().replace("-","");
        return qiniuUpload.upload(key,IOUtil.input2byte(is));
    }

    public static String upload(byte[] bytes) throws IOException {
        QiniuUpload qiniuUpload = QiniuManager.get();
        String key = UUID.randomUUID().toString().replace("-","");
        return qiniuUpload.upload(key,bytes);
    }

    public static String uploadImg(String fileName,byte[] bytes) throws IOException {
        String subfix ="";
        if(fileName.lastIndexOf(".")>0) {
           subfix= fileName.substring(fileName.lastIndexOf("."));
        }
        QiniuUpload qiniuUpload = QiniuManager.get();
        String key = UUID.randomUUID().toString().replace("-","")+subfix;
        return qiniuUpload.upload(key,bytes);
    }

    public static String getTouTiaoVideoUrl(String url ){
        String html  = HttpSessionUtils.httpGet(httpClient, url, "UTF-8");
        String videoUrl = RegExUtil.getFirstValue(html,"var\\s+mp4\\s*[=]\\s*[\"]([^\"]+)[\"];",1);
        if(videoUrl!=null && videoUrl.startsWith("//") && !videoUrl.contains("static.xyimg.net")) {
            return "http:" + videoUrl;
        }else{
            return null;
        }
    }
}
